import { BadRequestException, Injectable } from '@nestjs/common'
import { randomUUID } from 'crypto'
import * as qrcode from 'qrcode'

export interface QrCodeInfo {
  status:
    | 'noscan'
    | 'scan_wait_confirm'
    | 'scan_confirm'
    | 'scan_cancel'
    | 'expired'
  userInfo?: {
    userId: number
  }
}

const map = new Map<string, QrCodeInfo>()

@Injectable()
export class ScanLoginService {
  async generate() {
    const uuid = randomUUID()
    const dataUrl = await qrcode.toDataURL(
      `https://787b-27-223-76-238.ngrok-free.app/login?id=${uuid}`,
    )

    map.set(`qrcode_${uuid}`, { status: 'noscan' })

    return { dataUrl, uuid }
  }

  checkQrCodeStatus(uuid: string) {
    return map.get(`qrcode_${uuid}`)
  }

  scanQrCode(uuid: string) {
    console.log('scanQrCode', uuid)
    const info = map.get(`qrcode_${uuid}`)
    if (!info) {
      throw new BadRequestException('二维码已过期')
    }
    map.set(`qrcode_${uuid}`, { status: 'scan_wait_confirm' })
    return { status: 'scan-wait-confirm' }
  }

  confirmQrCode(uuid: string) {
    const info = map.get(`qrcode_${uuid}`)
    if (!info) {
      throw new BadRequestException('二维码已过期')
    }
    map.set(`qrcode_${uuid}`, {
      status: 'scan_confirm',
      userInfo: { userId: 1 },
    })
    return { status: 'scan-confirm' }
  }

  cancelQrCode(uuid: string) {
    const info = map.get(`qrcode_${uuid}`)
    if (!info) {
      throw new BadRequestException('二维码已过期')
    }
    map.set(`qrcode_${uuid}`, { status: 'scan_cancel' })
    return { status: 'scan-cancel' }
  }
}
